import requests
import customtkinter as ctk
from typing import Tuple, Optional
from config.config import UPDATE_CONFIG
from utils.utils import logger, get_current_version


def get_remote_version() -> Tuple[Optional[str], Optional[str], str, Optional[str], Optional[str]]:
    try:
        resp = requests.get(UPDATE_CONFIG["version_url"], timeout=UPDATE_CONFIG["timeout"])
        resp.raise_for_status()
        data = resp.json()
        return (
            data.get("version"),
            data.get("url"),
            data.get("changelog", ""),
            data.get("exe_sha256"),
            data.get("arch")
        )
    except Exception as e:
        logger.error(f"[远程版本] 获取失败: {e}", exc_info=True)
        return None, None, "", None, None

def show_update_dialog(current_ver: str, remote_ver: str, changelog: str) -> bool:
    root = ctk.CTk()
    root.title("发现新版本")
    root.geometry("520x460")
    root.resizable(False, False)
    root.attributes("-topmost", True)
    root.protocol("WM_DELETE_WINDOW", lambda: None)

    main_frame = ctk.CTkFrame(root)
    main_frame.pack(fill="both", expand=True, padx=15, pady=15)

    ctk.CTkLabel(main_frame, text="🎉 发现新版本！", font=("Microsoft YaHei", 18, "bold")).pack(pady=(10, 5))
    ctk.CTkLabel(main_frame, text=f"当前版本：{current_ver} → 新版本：{remote_ver}").pack()

    ctk.CTkLabel(main_frame, text="更新内容：", font=("Microsoft YaHei", 12, "underline"), anchor="w").pack(anchor="w", padx=10, pady=(15, 5))
    text_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
    text_frame.pack(fill="both", expand=True, padx=10, pady=(0, 15))
    textbox = ctk.CTkTextbox(text_frame, wrap="word", font=("Microsoft YaHei", 11))
    textbox.pack(side="left", fill="both", expand=True)
    textbox.insert("0.0", changelog if changelog else "暂无更新说明。")
    textbox.configure(state="disabled")
    scrollbar = ctk.CTkScrollbar(text_frame, command=textbox.yview)
    scrollbar.pack(side="right", fill="y")
    textbox.configure(yscrollcommand=scrollbar.set)

    result = {"update_now": False}

    def on_update():
        result["update_now"] = True
        root.destroy()

    def on_later():
        result["update_now"] = False
        root.destroy()

    button_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
    button_frame.pack(fill="x", pady=(0, 10))
    ctk.CTkButton(button_frame, text="立即更新", command=on_update, fg_color="green", width=120).pack(side="left", padx=(0, 15))
    ctk.CTkButton(button_frame, text="稍后再说", command=on_later, fg_color="gray", width=120).pack(side="right")

    root.grab_set()
    root.mainloop()
    return result["update_now"]